package lt.inkredibl.iit;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Point2D;

public class ObsAddPoints
	implements IComponentObserver, MouseListener
{
	private int _corner = -1;
	private boolean _seenMousePressed;
	private ICoordTransformer _ct;
	private Contour _contour;
	private IComponentObserver _cco;
	private Component _c;
	private ObsDragPoint _drag;

	public ObsAddPoints(Contour cont, ICoordTransformer ct, ObsDragPoint drag)
	{
		_ct = ct;
		_contour = cont;
		_drag = drag;
	}
	
	public void setConflicting(IComponentObserver cco)
	{
		_cco = cco;
	}
	
	/* (non-Javadoc)
	 * @see lt.inkredibl.iit.IComponentObserver#install(java.awt.Component)
	 */
	public void install(Component c)
	{
		_seenMousePressed = false;
		if (_c == null)
		{
			_c = c;
			if (_cco != null)
			{
				_cco.uninstall();
			}
			c.addMouseListener(this);
		}
		else
		{
			throw new IllegalStateException("Already installed on "+_c+" while trying to install on "+c);
		}
	}
	
	/* (non-Javadoc)
	 * @see lt.inkredibl.iit.IComponentObserver#uninstall()
	 */
	public void uninstall()
	{
		_c.removeMouseListener(this);
		if (_cco != null)
		{
			_cco.install(_c);
		}
		_c = null;
	}

	public void mouseClicked(MouseEvent e)
	{
			Point2D p = _ct.extractPoint(e);
	
			if (_corner >= 0)
			{
				Point2D pt = _contour.findPoint(p, _ct.ui2ic(5));
				if (pt != null)
				{
					_contour.setCorner(_corner, pt);
					_corner--;
					_c.repaint();
				}
			}
			else if (_seenMousePressed)
			{
				_contour.insertPoint(p);
				_c.repaint();
			}
	}

	public void mousePressed(MouseEvent e)
	{
		Point2D p = _contour.findPoint(_ct.extractPoint(e), _ct.ui2ic(5));
		
		if (p != null)
		{
			if (_corner >= 0)
			{
			}
			else
			{
				_drag.setPoint(p);
				_drag.install(_c);
			}
		}
		else
		{
			_seenMousePressed = true;
		}
	}

	public void mouseEntered(MouseEvent e)
	{
	}

	public void mouseExited(MouseEvent e)
	{
	}

	public void mouseReleased(MouseEvent e)
	{
	}

	public void pickCorners()
	{
		_corner = 3;
	}

	public void cancelPickCorners()
	{
		_corner = -1;
		_contour.invalidateCorners();
	}

}
